package com.ym.controller;

import com.ym.config.LockUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    //每个场景自定义前缀，防止key重复
    private static final String PREFIX_KEY = "test:lock:";

    @Autowired
    private LockUtils lockUtils;

    @Cacheable(value = "cache", key = "#string")
    @GetMapping("/testCache")
    public String testCache(@RequestParam("string") String string){
        return String.join(",", string.split(""));
    }

    @GetMapping("/testRedisson")
    public String testRedisson(@RequestParam("string") String string){
        boolean isLocked = lockUtils.lock(PREFIX_KEY + string,null);
        if(isLocked){
            try {
                //这里是业务逻辑
                TimeUnit.SECONDS.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //最终释放锁
                lockUtils.unlock(PREFIX_KEY + string);
            }
            return String.join("-", string.split(""));
        }
        return "error";
    }
}
